<template>
  <el-tabs type="card" v-model="activeName" >
    <el-tab-pane label="管理测试" name="first">
      <div class="main" style="height: 750px !important;" >
<!--        <div class="topBlock">-->

<!--          <el-button @click="deleteByIds" size="medium" icon="el-icon-delete-solid"></el-button>-->
<!--                    <el-button @click="" size="medium" icon="el-icon-plus" ></el-button>-->
<!--        </div>-->
        <div class="table">

          <el-table
              :header-cell-style="{'border': 'none',textAlign:'start'}"
              :cell-style="{'border': 'true',textAlign:'start',}"
              :data="examListWithDuration.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
              border
              @selection-change="handleSelectionChange"

          >
            <el-table-column type="expand" height="80">
              <template slot-scope="props">
                <el-form label-position="left" class="demo-table-expand">
                  <el-form-item label="- 试卷描述:">
                    <span>{{ props.row.paper.paperDesc }}</span>
                  </el-form-item>
                  <el-form-item label="- 发起时间:">
                    <span>{{ props.row.updateTime }}</span>
                  </el-form-item>
                  <el-form-item label="- 持续时间:">
                    <span>{{ props.row.duration }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号"/>
            <el-table-column label="测试名" prop="examName"/>
            <el-table-column label="试卷名" prop="paper.paperTitle"/>
            <el-table-column prop="startTime" label="开考时间" :formatter="formatExamStartTime"></el-table-column>
            <el-table-column prop="endTime" label="交卷时间" :formatter="formatExamEndTime"></el-table-column>
            <el-table-column label="预览时间" prop="viewTime" :formatter="formatExamViewTime"/>

            <el-table-column prop="handleClass.studentList" label="交卷数/总人数">
              <template slot-scope="scope">
                <a style="color:#409EFF;cursor:pointer" @click="viewStu(scope.row)">
                  {{ scope.row.submitCount }}
                </a>
                / {{ scope.row.handleClass.studentList.length }}
              </template>
            </el-table-column>
            <el-table-column prop="handleClass.school.schoolName" label="学校名称"></el-table-column>
            <el-table-column prop="handleClass.majorName" label="专业名称"></el-table-column>
            <el-table-column prop="handleClass.year" label="年级"></el-table-column>
            <el-table-column prop="handleClass.classNum" label="班级">
              <template slot-scope="scope">{{ scope.row.handleClass.classNum }}班</template>
            </el-table-column>
            <el-table-column prop="updateTime" label="发布时间">
              <template slot-scope="scope">
                {{ formatUpdateTime(scope.row.updateTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="id" label="操作" width="250">
              <template slot-scope="scope">
                <!--                <el-button-group>-->
                <template v-if="scope.row.correctStatus">

                  <el-button disabled type="success" @click="toCorrectAnswerPaper(scope.row)" size="mini"
                             icon="el-icon-document">
                    已批改
                  </el-button>

                </template>

                <div v-else>

                  <el-button v-if="scope.row.handleClass.studentList.length!=0&&scope.row.submitCount>0" type="primary"
                             @click="toCorrectAnswerPaper(scope.row)" size="mini" icon="el-icon-document">
                    批改试卷
                  </el-button> <el-button v-else disabled type="primary" size="mini" icon="el-icon-document">批改试卷</el-button>


                  <el-button @click="viewStuForSendBack(scope.row)"
                             v-if="scope.row.handleClass.studentList.length!=0&&scope.row.submitCount>0"
                             type="primary" size="mini" icon="el-icon-document">
                    打回答卷
                  </el-button> <el-button v-else disabled type="primary" size="mini" icon="el-icon-document">打回答卷</el-button>


                </div>


              </template>
            </el-table-column>
          </el-table>
        </div>

      </div>
      <div class="footers">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="prev, pager, next, total, sizes"
            :total="examListWithDuration.length"
            :current-page="currentPage"
            :page-sizes="[10,20]"
        >
        </el-pagination>
      </div>

      <!--    查看考生列表隐藏框-->
      <el-dialog
          title="考生列表"
          :visible.sync="viewStuVisible"
          width="30%"
      >
        <el-table :data="viewStuData">
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column prop="userName" label="姓名"></el-table-column>
          <el-table-column prop="submitTime" label="交卷时间">
            <template slot-scope="scope">
              <span v-if="scope.row.submitTime" style="color: #409EFF"> {{ scope.row.submitTime }}</span>
              <span v-else> 未交卷 </span>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="viewStuVisible = false">确 定</el-button>
      </span>
      </el-dialog>

      <!--      打回试卷考生列表隐藏框-->
      <el-dialog
          title="考生列表"
          :visible.sync="viewStuVisibleForSendBack"
          width="30%"
      >
        <el-table :data="viewStuData">
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column prop="userName" label="姓名"></el-table-column>
          <el-table-column prop="submitTime" label="交卷时间">
            <template slot-scope="scope">
              <span v-if="scope.row.submitTime" style="color: #409EFF"> {{ scope.row.submitTime }}</span>
              <span v-else> 未交卷 </span>
            </template>
          </el-table-column>
          <el-table-column prop="submitTime" label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.submitTime" type="primary" @click="sendBackAnswerPaper(scope.row)"> 打回
              </el-button>
              <el-button v-else disabled> 打回</el-button>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="viewStuVisibleForSendBack = false">确 定</el-button>
      </span>
      </el-dialog>


    </el-tab-pane>


    <!--    <el-tab-pane label="批改答卷" name="second">配置管理</el-tab-pane>-->

  </el-tabs>


</template>

<script>
import {delExamByIdsApi, getExamListApi} from "@/api/Exam";
import {delHandleClassByIdsApi} from "@/api/handleClass";
import notification from "@/utils/notification";
import {getAnswerPaperInfoListApi} from "@/api/CorrectAnswerPaper";
import {sendBackAnswerPaperApi} from "@/api/AnswerPaper";
import {Message} from "element-ui";
import {Storage} from '@/utils/localStorage'
const storage = new Storage();

export default {
  name: "ExamListView",
  data() {
    return {
      userData: [],
      //分页数据
      currentPage: 1, //初始页
      pageSize: 10, //    每页的数据
      activeName: 'first',
      //通过created 获取examList列表 table绑定的并不是当前examList
      examList: [],
      multipleTable: [],
      //查看考生列表的隐藏框逻辑量
      viewStuVisible: false,
      viewStuVisibleForSendBack: false,
      //查看学生列表的数据变量
      viewStuData: [],
      //传递examId间接量 用于打回答卷
      examIdTemp: '',
    };

  },
  methods: {
    handleSizeChange(size) {
      // console.log(size, 'size');
      this.pageSize = size;
      console.log(this.pageSize); //改变每页显示数据条数
    },
    handleCurrentChange(currentPage) {
      // console.log(currentPage, 'currentPage');
      this.currentPage = currentPage;
      console.log(this.currentPage); //点击第几页
    },
    //打回答卷
    sendBackAnswerPaper(row) {
      // console.info("打回答卷,student:",row)
      // console.info("打回examId",)
      sendBackAnswerPaperApi({examId: this.examIdTemp, studentId: row.id}).then(res => {
        if (res.data.code == 200) {
          //打回成功后 在这个临时数据列表中删除 当前对象
          this.viewStuData = this.viewStuData.filter(obj => obj.id !== row.id);
          //刷新列表 以免之前缓存导致假信息报错
          this.getExamList()
          notification.ntfCommonSuccess("提示", res.data.msg);
          console.info("响应信息", res)
        }
      })
    },
    toCorrectAnswerPaper(row) {

      if (new Date(row.endTime) > new Date()) {
        Message.warning('考试未结束！')
        return
      }

      console.info("开始批卷", row)
      this.$router.push({
        name: 'CorrectAnswerPaperView',
        params: {
          exam: row,
        },
      })
      // getAnswerPaperInfoListApi(row)
    },
    viewStuForSendBack(row) {
      this.examIdTemp = row.id
      this.viewStuData = row.handleClass.studentList
      this.viewStuVisibleForSendBack = true
      // 这里可以根据具体需求判断点击的元素
      // 例如，可以使用事件委托来判断点击的是哪一列
      // 然后执行相应的操作
      console.log('点击了表格中的一列');
      console.log(row);

    },
    viewStu(row) {
      this.viewStuData = row.handleClass.studentList
      this.viewStuVisible = true
      // 这里可以根据具体需求判断点击的元素
      // 例如，可以使用事件委托来判断点击的是哪一列
      // 然后执行相应的操作
      console.log('点击了表格中的一列');
      console.log(row);

    },
    //美观考虑 考试时间的格式化 2023-06-10 00:00 --> 06-10 00:00
    formatExamEndTime(row) {
      // 获取原始时间戳
      const timestamp = new Date(row.endTime);
      // 获取当前时间的年份
      const currentYear = new Date().getFullYear();
      // 获取时间字符串中的年份
      const year = timestamp.getFullYear();
      // 如果当前时间的年份与时间字符串中的年份相同，只显示月日时分，否则显示年月日时分
      if (year === currentYear) {
        return `${(timestamp.getMonth() + 1).toString().padStart(2, '0')}-${timestamp.getDate().toString().padStart(2, '0')} ${timestamp.getHours().toString().padStart(2, '0')}:${timestamp.getMinutes().toString().padStart(2, '0')}`
      } else {
        return row.endTime;
      }
    },
    formatExamStartTime(row) {
      // 获取原始时间戳
      const timestamp = new Date(row.startTime);
      // 获取当前时间的年份
      const currentYear = new Date().getFullYear();
      // 获取时间字符串中的年份
      const year = timestamp.getFullYear();
      // 如果当前时间的年份与时间字符串中的年份相同，只显示月日时分，否则显示年月日时分
      if (year === currentYear) {
        return `${(timestamp.getMonth() + 1).toString().padStart(2, '0')}-${timestamp.getDate().toString().padStart(2, '0')} ${timestamp.getHours().toString().padStart(2, '0')}:${timestamp.getMinutes().toString().padStart(2, '0')}`
      } else {
        return row.startTime;
      }
    },
    formatExamViewTime(row) {
      // 获取原始时间戳
      const timestamp = new Date(row.viewTime);
      // 获取当前时间的年份
      const currentYear = new Date().getFullYear();
      // 获取时间字符串中的年份
      const year = timestamp.getFullYear();
      // 如果当前时间的年份与时间字符串中的年份相同，只显示月日时分，否则显示年月日时分
      if (year === currentYear) {
        return `${(timestamp.getMonth() + 1).toString().padStart(2, '0')}-${timestamp.getDate().toString().padStart(2, '0')} ${timestamp.getHours().toString().padStart(2, '0')}:${timestamp.getMinutes().toString().padStart(2, '0')}`
      } else {
        return row.viewTime;
      }
    },
    formatUpdateTime(timestamp) {
      if (!timestamp) {
        return '';
      }
      const targetTime = Date.parse(timestamp); // 转换成时间戳
      const now = new Date().getTime(); // 获取当前时间戳
      const diff = Math.abs(now - targetTime); // 获取时间差的绝对值
      const diffMinutes = Math.floor(diff / (1000 * 60)); // 获取时间差的分钟数
      if (diffMinutes < 5) {
        return '刚刚'; // 小于5分钟，表示刚刚发布
      } else if (diffMinutes < 60) {
        return `${diffMinutes} 分钟前`; // 不超过1小时，显示几分钟前
      } else {
        const diffHours = Math.floor(diffMinutes / 60); // 超过1小时，显示几小时前
        if (diffHours < 24) {
          return `${diffHours} 小时前`; // 不超过1天，显示几小时前
        } else {
          const diffDays = Math.floor(diffHours / 24); // 超过1天，显示几天前
          return `${diffDays} 天前`;
        }
      }
    },
    //批量删除
    async deleteByIds() {
      const idArr = [];
      // console.info( this.multipleTable)
      for (let obj of this.multipleTable) {
        idArr.push(obj.id);
      }
      console.info(idArr)
      if (idArr.length !== 0) {
        let confirm = await this.$myConfirm("确认操作？")
        if (confirm) {
          delExamByIdsApi(idArr).then(res => {
            if (res.data.code == 200) {
              notification.ntfCommonSuccess("提示", res.data.msg);
              this.getExamList()
            }
          })
        }
      }
    },
    //多选时每列的对象保存在multipleTable中
    handleSelectionChange(val) {
      this.multipleTable = val
      // console.info(this.multipleTable)
    },
    getExamList() {
      this.userData = storage.getItem("user")
      console.log( this.userData)
      getExamListApi({teacherId: this.userData.id}).then(res => {
        if (res.data.code == 200) {
          console.info("this.ExamList", res.data.data)
          this.examList = res.data.data

        }
      })
    }
  },
  created() {
    this.getExamList()
  },
  computed: {
    //将examList转换为带有duration的对象数组
    //在table中绑定的是examListWithDuration
    examListWithDuration() {
      return this.examList.map((row) => {
        const start = new Date(row.startTime); // 创建开始时间的 Date 对象
        const end = new Date(row.endTime); // 创建结束时间的 Date 对象
        const diff = end - start; // 持续时间 = 结束时间 - 开始时间
        const durationInMs = Math.abs(diff); // 取绝对值，避免差值为负数
        const durationInMinutes = durationInMs / (1000 * 60); // 将持续时间转换为分钟
        const durationInHours = Math.floor(durationInMinutes / 60); // 将分钟转换为小时并取整
        const remainingMinutes = durationInMinutes % 60; // 计算剩余的分钟数
        return {
          ...row,
          duration: `${durationInHours} 小时 ${remainingMinutes} 分钟` // 添加新的属性 duration，表示持续时间
        }
      });
    }
  }
}
</script>

<style scoped>

.footers {
  position: relative;
  display: flex;
  align-items: end;
  justify-content: center;
  width: 100%;
  height: 40px;

}

.main {


  /*background-color: #42b983;*/
}

.topBlock {
  display: flex;
  /*background-color: #42b983;*/
  height: 46px;
  align-items: center;
  justify-content: start;
  /*border-left: 1px solid #e6e6e6;*/
  /*border-right: 1px solid #e6e6e6;*/
  /*background-color: #f5f5f5;*/
  border-radius: 5px;
}
</style>